/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  NativeModules,
  DeviceEventEmitter,
  View
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component{
  constructor(props){
    super(props);
    this.state={
      isclick:'Welcome to React Native--toast !',
      dialog:'Welcome to React Native--dialog !'
    }
  }
  componentWillMount() {
      DeviceEventEmitter.addListener('getResultFromAndroid1', function  (msg) {
        NativeModules.MyNativeModule.rnCallNativeToast('我是返回值'+msg.key);
      });
      DeviceEventEmitter.addListener('getResultFromAndroid2', function  (msg) {
        NativeModules.MyNativeModule.rnCallNativeToast('我是返回值'+msg.key);
      });
  }
  show(){
    NativeModules.MyNativeModule.rnCallNativeToast('调用原生方法的Demo');
    // alert('调用android弹框');
    this.setState({
      isclick:'我已经被点击了，toast'
    })
  }

  dialog(){
    NativeModules.MyNativeModule.rnCallNativeDialog('调用原生方法的Demo');
    // alert('调用android弹框');
    this.setState({
      dialog:'我已经被点击了，dialog'
    })
  }
  
  getCallBackTime() {
    NativeModules.MyNativeModule.callBackTime("callback",
        (msg) => {
            NativeModules.MyNativeModule.rnCallNativeToast(msg);
        }
    );
  }

  getPromiseTime() {
    NativeModules.MyNativeModule.sendPromiseTime("promiss").then(msg=> {
        NativeModules.MyNativeModule.rnCallNativeToast("Promise收到消息:" + "\n" + "年龄:" + msg.age + "时间:" + msg.time+ "姓名:" + msg.name);
    }).catch(error=> {
        console.log(error);
    });
  }
  render() {
    return (
      <View style={styles.container}>
        <Text onPress={this.show.bind(this)} style={styles.welcome}>
          {this.state.isclick}
        </Text>
        <Text onPress={this.dialog.bind(this)} style={styles.welcome}>
          {this.state.dialog}
        </Text>
        <Text onPress={this.getCallBackTime.bind(this)} style={styles.welcome}>
          callback调用
        </Text>
        <Text onPress={this.getPromiseTime.bind(this)} style={styles.welcome}>
          promiss调用
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
